package top.baselitch.liteorm;

import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import top.baselitch.liteorm.annotation.FieldAutoIncrement;
import top.baselitch.liteorm.annotation.FieldUnique;
import top.baselitch.liteorm.annotation.TableField;
import top.baselitch.liteorm.annotation.TablePrimaryKey;

public class FieldModel {
    private String fieldName;//字段名
    private String fieldType;//字段类型
    private List<String> fieldConstraints;//字段约束
    private FieldModel(Builder builder){
        this.fieldName = builder.fieldName;
        this.fieldType = builder.fieldType;
        this.fieldConstraints = builder.fieldConstraints;
    }
    public static class Builder{
        private Field field;
        private Annotation[] annotations;
        private String fieldName;
        private String fieldType;
        private List<String> fieldConstraints;
        public Builder(Field field){
            this.field = field;
            annotations = field.getAnnotations();
        }
        public FieldModel builder(){
            String typeName = field.getType().getName();
            if(typeName.equals("int")){
                this.fieldType = "INTEGER";
            }else if(typeName.equals("java.lang.String")){
                this.fieldType = "VARCHAR";
            }
            fieldConstraints = new ArrayList<>();
            for(Annotation annotation : annotations){
                parseTableFieldAnnotation(annotation);
            }
            return new FieldModel(this);
        }

        /**
         * 解析表字段注解
         * @param annotation 注解
         */
        private void parseTableFieldAnnotation(Annotation annotation){
            if(annotation instanceof TableField){
                this.fieldName = ((TableField) annotation).value();
            }else if(annotation instanceof TablePrimaryKey){
                this.fieldConstraints.add(0,"PRIMARY KEY");
            }else if(annotation instanceof FieldAutoIncrement){
                this.fieldConstraints.add(fieldConstraints.size(),"AUTOINCREMENT");
            }else if(annotation instanceof FieldUnique){
                this.fieldConstraints.add("UNIQUE");
            }
        }
    }

    public String builderSql(){
        StringBuilder sb = new StringBuilder();
        sb.append(fieldName);
        sb.append(" ");
        sb.append(fieldType);
        sb.append(" ");
        int constraintsLenth = fieldConstraints.size();
        int ind = 0;
        for(String constraints : fieldConstraints){
            sb.append(constraints);
            sb.append(ind==constraintsLenth-1?"":" ");
            ind++;
        }
        return sb.toString();
    }
}
